//
//  QrScanViewController.swift
//  bbq_ios
//
//  Created by 杨洪河 on 15/5/12.
//  Copyright (c) 2015年 biaobaiqiang. All rights reserved.
//

import UIKit
import Foundation
import AVFoundation

class QrScanViewController: UIViewController ,AVCaptureMetadataOutputObjectsDelegate {
    
    
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    let session = AVCaptureSession()
    var layer: AVCaptureVideoPreviewLayer?
    var screenWidth = UIScreen.mainScreen().bounds.width
    var screenHeight = UIScreen.mainScreen().bounds.height
    var line: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "二维码扫描"
        
        self.view.backgroundColor = UIColor.whiteColor()
        let imageView = UIImageView(frame:CGRectMake(screenWidth / 2 - 110, 90, 220, 220))
        imageView.image = UIImage(named:"qr_capture")
        self.view.addSubview(imageView)
        
        line = UIImageView(frame:CGRectMake(screenWidth / 2 - 105, 90, 210, 4))
        line.image = UIImage(named:"qr_scan_line")
        self.view.addSubview(line)
        
        var y = 90;
        
        // 提示文字
        let labIntroudction = UILabel(frame:CGRectMake(screenWidth / 2 - 125, 300, 290, 50))
        labIntroudction.backgroundColor = UIColor.clearColor()
        labIntroudction.numberOfLines = 2
        labIntroudction.textColor = UIColor.whiteColor()
        labIntroudction.text = "将二维码放入框内，即可自动识别"
        self.view.addSubview(labIntroudction)
        
        // 闪光灯操作
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.BlackTranslucent
        let item = UIBarButtonItem(image:(UIImage(named:"flash_open")), style:(UIBarButtonItemStyle.Bordered), target:self, action:(Selector("flash")))
        let flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem : (UIBarButtonSystemItem.FlexibleSpace), target: self, action: nil)
        toolBar.items = [flexibleSpaceItem,flexibleSpaceItem,item,flexibleSpaceItem, flexibleSpaceItem]
        toolBar.frame = CGRectMake(0, screenHeight-60, 320, 60)
        self.view.addSubview(toolBar)
        
        startAnim()
    }
    
    // 扫描线的持续动画
    func startAnim() {
        UIView.animateWithDuration(3.0,
            delay: 0.0,
            options: .CurveEaseInOut | .AllowUserInteraction,
            animations: {
                self.line.frame = CGRectMake(self.screenWidth / 2 - 105, 305, 210, 4)
            },
            completion: { finished in
                self.line.frame = CGRectMake(self.screenWidth / 2 - 105, 90, 210, 4)
                self.startAnim()
        })
    }
    
    // 对闪关灯的操作
    func flash(){
        if !device.flashActive && device.hasFlash && device.isFlashModeSupported(AVCaptureFlashMode.On) {
            self.device.lockForConfiguration(nil)
            self.device.torchMode = AVCaptureTorchMode.On
            self.device.flashMode = AVCaptureFlashMode.On
        } else {
            self.device.torchMode = AVCaptureTorchMode.Off
            self.device.flashMode = AVCaptureFlashMode.Off
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 初始化相机进行扫描
        self.setupCamera()
        self.session.startRunning()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
    }
    
    func setupCamera(){
        self.session.sessionPreset = AVCaptureSessionPresetHigh
        var error : NSError?
        let input = AVCaptureDeviceInput(device: device, error: &error)
        if (error != nil) {
            println(error?.description)
            return
        }
        if session.canAddInput(input) {
            session.addInput(input)
        }
        layer = AVCaptureVideoPreviewLayer(session: session)
        layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
        layer!.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        self.view.layer.insertSublayer(self.layer, atIndex: 0)
        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        if session.canAddOutput(output) {
            session.addOutput(output)
            output.metadataObjectTypes = [AVMetadataObjectTypeQRCode];
            // 设置二维码的有效识别区域
            output.rectOfInterest = CGRectMake(90 / self.screenHeight , ((self.screenWidth - 220) / 2) / self.screenWidth, 220 / self.screenHeight ,220 / self.screenWidth)
        }
        
        session.startRunning()
    }
    
    
    
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
        var stringValue:String?
        if metadataObjects.count > 0 {
            var metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            stringValue = metadataObject.stringValue
        }
        if stringValue == nil {
            return
        }
        self.session.stopRunning()
        
        let path = NSBundle.mainBundle().pathForResource("qr_sacn", ofType: "mp3")
        let player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil)
        
        player.play()
        
        println("code is \(stringValue)")
        
        var alertView = UIAlertView()
        alertView.delegate=self
        alertView.title = "二维码"
        alertView.message = "扫到的二维码内容为:\(stringValue)"
        alertView.addButtonWithTitle("确认")
        alertView.show()
    }
    
}

extension QrScanViewController: UIAlertViewDelegate {
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        self.session.startRunning()
    }
}
